"""
移动端UI组件库

提供移动端优化的UI组件，包括：
- 触摸友好的交互组件
- 响应式布局组件
- 移动端特定的导航组件
- 手势支持组件
- 性能优化组件
"""
from typing import Dict, List, Any, Optional, Callable
from dataclasses import dataclass, field
from enum import Enum
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
components_logger = logging.getLogger('mobile_components')


class ComponentType(Enum):
    """组件类型枚举"""
    BUTTON = "button"
    INPUT = "input"
    CARD = "card"
    LIST = "list"
    NAVIGATION = "navigation"
    MODAL = "modal"
    TABS = "tabs"
    FORM = "form"
    CHART = "chart"
    MEDIA = "media"


class ComponentSize(Enum):
    """组件尺寸枚举"""
    SMALL = "small"
    MEDIUM = "medium"
    LARGE = "large"
    XLARGE = "xlarge"


class ComponentVariant(Enum):
    """组件变体枚举"""
    PRIMARY = "primary"
    SECONDARY = "secondary"
    SUCCESS = "success"
    WARNING = "warning"
    ERROR = "error"
    INFO = "info"


@dataclass
class ComponentProps:
    """组件属性"""
    component_id: str
    component_type: ComponentType
    size: ComponentSize = ComponentSize.MEDIUM
    variant: ComponentVariant = ComponentVariant.PRIMARY
    disabled: bool = False
    loading: bool = False
    visible: bool = True
    classes: List[str] = field(default_factory=list)
    styles: Dict[str, str] = field(default_factory=dict)
    attributes: Dict[str, Any] = field(default_factory=dict)
    events: Dict[str, str] = field(default_factory=dict)
    children: List['ComponentProps'] = field(default_factory=list)


class MobileComponentLibrary:
    """移动端组件库"""
    
    def __init__(self):
        # 组件模板
        self.component_templates = {}
        self._initialize_component_templates()
        
        # 主题配置
        self.theme_config = {
            'colors': {
                'primary': '#2196F3',
                'secondary': '#757575',
                'success': '#4CAF50',
                'warning': '#FF9800',
                'error': '#F44336',
                'info': '#00BCD4',
                'background': '#FFFFFF',
                'surface': '#F5F5F5',
                'text_primary': '#212121',
                'text_secondary': '#757575'
            },
            'spacing': {
                'xs': '4px',
                'sm': '8px',
                'md': '16px',
                'lg': '24px',
                'xl': '32px'
            },
            'typography': {
                'font_family': '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                'font_sizes': {
                    'xs': '12px',
                    'sm': '14px',
                    'md': '16px',
                    'lg': '18px',
                    'xl': '20px',
                    'xxl': '24px'
                },
                'line_heights': {
                    'tight': '1.2',
                    'normal': '1.5',
                    'relaxed': '1.8'
                }
            },
            'shadows': {
                'sm': '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)',
                'md': '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)',
                'lg': '0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23)'
            },
            'border_radius': {
                'sm': '4px',
                'md': '8px',
                'lg': '12px',
                'xl': '16px',
                'full': '50%'
            }
        }
        
        # 响应式断点
        self.breakpoints = {
            'xs': '0px',
            'sm': '576px',
            'md': '768px',
            'lg': '992px',
            'xl': '1200px'
        }
    
    def _initialize_component_templates(self):
        """初始化组件模板"""
        # 按钮组件模板
        self.component_templates[ComponentType.BUTTON] = {
            'base_classes': ['btn', 'touch-target'],
            'size_classes': {
                ComponentSize.SMALL: ['btn-sm'],
                ComponentSize.MEDIUM: ['btn-md'],
                ComponentSize.LARGE: ['btn-lg'],
                ComponentSize.XLARGE: ['btn-xl']
            },
            'variant_classes': {
                ComponentVariant.PRIMARY: ['btn-primary'],
                ComponentVariant.SECONDARY: ['btn-secondary'],
                ComponentVariant.SUCCESS: ['btn-success'],
                ComponentVariant.WARNING: ['btn-warning'],
                ComponentVariant.ERROR: ['btn-error'],
                ComponentVariant.INFO: ['btn-info']
            },
            'state_classes': {
                'disabled': ['btn-disabled'],
                'loading': ['btn-loading']
            },
            'default_attributes': {
                'type': 'button',
                'role': 'button',
                'tabindex': '0'
            },
            'touch_attributes': {
                'data-touch-feedback': 'true',
                'data-ripple': 'true'
            }
        }
        
        # 输入框组件模板
        self.component_templates[ComponentType.INPUT] = {
            'base_classes': ['input', 'touch-friendly'],
            'size_classes': {
                ComponentSize.SMALL: ['input-sm'],
                ComponentSize.MEDIUM: ['input-md'],
                ComponentSize.LARGE: ['input-lg'],
                ComponentSize.XLARGE: ['input-xl']
            },
            'variant_classes': {
                ComponentVariant.PRIMARY: ['input-primary'],
                ComponentVariant.ERROR: ['input-error'],
                ComponentVariant.SUCCESS: ['input-success']
            },
            'state_classes': {
                'disabled': ['input-disabled'],
                'loading': ['input-loading']
            },
            'default_attributes': {
                'autocomplete': 'off',
                'spellcheck': 'false'
            },
            'mobile_attributes': {
                'data-mobile-input': 'true',
                'data-auto-resize': 'true'
            }
        }
        
        # 卡片组件模板
        self.component_templates[ComponentType.CARD] = {
            'base_classes': ['card', 'touch-card'],
            'size_classes': {
                ComponentSize.SMALL: ['card-sm'],
                ComponentSize.MEDIUM: ['card-md'],
                ComponentSize.LARGE: ['card-lg'],
                ComponentSize.XLARGE: ['card-xl']
            },
            'variant_classes': {
                ComponentVariant.PRIMARY: ['card-primary'],
                ComponentVariant.SECONDARY: ['card-secondary']
            },
            'default_attributes': {
                'role': 'article'
            },
            'touch_attributes': {
                'data-swipeable': 'true',
                'data-tap-highlight': 'true'
            }
        }
        
        # 列表组件模板
        self.component_templates[ComponentType.LIST] = {
            'base_classes': ['list', 'mobile-list'],
            'variant_classes': {
                ComponentVariant.PRIMARY: ['list-primary'],
                ComponentVariant.SECONDARY: ['list-secondary']
            },
            'default_attributes': {
                'role': 'list'
            },
            'mobile_attributes': {
                'data-virtual-scroll': 'true',
                'data-pull-refresh': 'true'
            }
        }
        
        # 导航组件模板
        self.component_templates[ComponentType.NAVIGATION] = {
            'base_classes': ['nav', 'mobile-nav'],
            'variant_classes': {
                ComponentVariant.PRIMARY: ['nav-primary'],
                ComponentVariant.SECONDARY: ['nav-secondary']
            },
            'default_attributes': {
                'role': 'navigation'
            },
            'mobile_attributes': {
                'data-swipe-nav': 'true',
                'data-sticky': 'true'
            }
        }
    
    def create_component(self, component_type: ComponentType, 
                        props: Dict[str, Any]) -> ComponentProps:
        """创建组件"""
        try:
            component_id = props.get('id', f"{component_type.value}_{id(props)}")
            
            component = ComponentProps(
                component_id=component_id,
                component_type=component_type,
                size=ComponentSize(props.get('size', 'medium')),
                variant=ComponentVariant(props.get('variant', 'primary')),
                disabled=props.get('disabled', False),
                loading=props.get('loading', False),
                visible=props.get('visible', True),
                classes=props.get('classes', []),
                styles=props.get('styles', {}),
                attributes=props.get('attributes', {}),
                events=props.get('events', {}),
                children=[]
            )
            
            # 应用组件模板
            self._apply_component_template(component)
            
            # 添加子组件
            for child_data in props.get('children', []):
                child_type = ComponentType(child_data.get('type', 'button'))
                child_component = self.create_component(child_type, child_data)
                component.children.append(child_component)
            
            components_logger.info(f"组件创建成功: {component_id}")
            return component
            
        except Exception as e:
            components_logger.error(f"组件创建失败: {str(e)}")
            return ComponentProps(
                component_id="error_component",
                component_type=ComponentType.BUTTON
            )
    
    def _apply_component_template(self, component: ComponentProps):
        """应用组件模板"""
        template = self.component_templates.get(component.component_type, {})
        
        # 基础类
        base_classes = template.get('base_classes', [])
        component.classes.extend(base_classes)
        
        # 尺寸类
        size_classes = template.get('size_classes', {}).get(component.size, [])
        component.classes.extend(size_classes)
        
        # 变体类
        variant_classes = template.get('variant_classes', {}).get(component.variant, [])
        component.classes.extend(variant_classes)
        
        # 状态类
        state_classes = template.get('state_classes', {})
        if component.disabled:
            component.classes.extend(state_classes.get('disabled', []))
        if component.loading:
            component.classes.extend(state_classes.get('loading', []))
        
        # 默认属性
        default_attrs = template.get('default_attributes', {})
        for key, value in default_attrs.items():
            if key not in component.attributes:
                component.attributes[key] = value
        
        # 触摸属性
        touch_attrs = template.get('touch_attributes', {})
        component.attributes.update(touch_attrs)
        
        # 移动端属性
        mobile_attrs = template.get('mobile_attributes', {})
        component.attributes.update(mobile_attrs)
    
    def render_component(self, component: ComponentProps) -> str:
        """渲染组件为HTML"""
        try:
            # 根据组件类型选择渲染方法
            render_methods = {
                ComponentType.BUTTON: self._render_button,
                ComponentType.INPUT: self._render_input,
                ComponentType.CARD: self._render_card,
                ComponentType.LIST: self._render_list,
                ComponentType.NAVIGATION: self._render_navigation,
                ComponentType.MODAL: self._render_modal,
                ComponentType.TABS: self._render_tabs,
                ComponentType.FORM: self._render_form
            }
            
            render_method = render_methods.get(component.component_type, self._render_generic)
            return render_method(component)
            
        except Exception as e:
            components_logger.error(f"组件渲染失败: {str(e)}")
            return f'<div class="error">组件渲染错误: {str(e)}</div>'
    
    def _render_button(self, component: ComponentProps) -> str:
        """渲染按钮组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        attributes = []
        for key, value in component.attributes.items():
            attributes.append(f'{key}="{value}"')
        
        events = []
        for event, handler in component.events.items():
            events.append(f'{event}="{handler}"')
        
        attrs_str = ' '.join(attributes + events)
        style_str = f' style="{styles}"' if styles else ''
        
        # 按钮内容
        content = component.attributes.get('text', '按钮')
        if component.loading:
            content = f'<span class="loading-spinner"></span> {content}'
        
        return f'''
<button id="{component.component_id}" 
        class="{classes}" 
        {attrs_str}{style_str}>
    {content}
</button>'''
    
    def _render_input(self, component: ComponentProps) -> str:
        """渲染输入框组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        attributes = []
        for key, value in component.attributes.items():
            if key not in ['label', 'placeholder', 'helper_text']:
                attributes.append(f'{key}="{value}"')
        
        attrs_str = ' '.join(attributes)
        style_str = f' style="{styles}"' if styles else ''
        
        # 输入框包装
        label = component.attributes.get('label', '')
        placeholder = component.attributes.get('placeholder', '')
        helper_text = component.attributes.get('helper_text', '')
        
        label_html = f'<label for="{component.component_id}" class="input-label">{label}</label>' if label else ''
        helper_html = f'<div class="input-helper">{helper_text}</div>' if helper_text else ''
        
        return f'''
<div class="input-group">
    {label_html}
    <input id="{component.component_id}" 
           class="{classes}" 
           placeholder="{placeholder}"
           {attrs_str}{style_str}>
    {helper_html}
</div>'''
    
    def _render_card(self, component: ComponentProps) -> str:
        """渲染卡片组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        attributes = []
        for key, value in component.attributes.items():
            if key not in ['title', 'subtitle', 'content']:
                attributes.append(f'{key}="{value}"')
        
        attrs_str = ' '.join(attributes)
        style_str = f' style="{styles}"' if styles else ''
        
        # 卡片内容
        title = component.attributes.get('title', '')
        subtitle = component.attributes.get('subtitle', '')
        content = component.attributes.get('content', '')
        
        title_html = f'<div class="card-title">{title}</div>' if title else ''
        subtitle_html = f'<div class="card-subtitle">{subtitle}</div>' if subtitle else ''
        content_html = f'<div class="card-content">{content}</div>' if content else ''
        
        # 渲染子组件
        children_html = ''
        for child in component.children:
            children_html += self.render_component(child)
        
        return f'''
<div id="{component.component_id}" 
     class="{classes}" 
     {attrs_str}{style_str}>
    <div class="card-header">
        {title_html}
        {subtitle_html}
    </div>
    <div class="card-body">
        {content_html}
        {children_html}
    </div>
</div>'''
    
    def _render_list(self, component: ComponentProps) -> str:
        """渲染列表组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        attributes = []
        for key, value in component.attributes.items():
            if key not in ['items']:
                attributes.append(f'{key}="{value}"')
        
        attrs_str = ' '.join(attributes)
        style_str = f' style="{styles}"' if styles else ''
        
        # 列表项
        items = component.attributes.get('items', [])
        items_html = ''
        
        for item in items:
            item_classes = 'list-item touch-target'
            if item.get('active'):
                item_classes += ' active'
            
            item_content = item.get('content', '')
            item_icon = item.get('icon', '')
            item_action = item.get('action', '')
            
            icon_html = f'<span class="list-item-icon">{item_icon}</span>' if item_icon else ''
            action_html = f'<span class="list-item-action">{item_action}</span>' if item_action else ''
            
            items_html += f'''
<div class="{item_classes}" data-value="{item.get('value', '')}">
    {icon_html}
    <div class="list-item-content">{item_content}</div>
    {action_html}
</div>'''
        
        return f'''
<div id="{component.component_id}" 
     class="{classes}" 
     {attrs_str}{style_str}>
    {items_html}
</div>'''
    
    def _render_navigation(self, component: ComponentProps) -> str:
        """渲染导航组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        attributes = []
        for key, value in component.attributes.items():
            if key not in ['items', 'position']:
                attributes.append(f'{key}="{value}"')
        
        attrs_str = ' '.join(attributes)
        style_str = f' style="{styles}"' if styles else ''
        
        # 导航项
        items = component.attributes.get('items', [])
        position = component.attributes.get('position', 'bottom')
        
        nav_items_html = ''
        for item in items:
            item_classes = 'nav-item touch-target'
            if item.get('active'):
                item_classes += ' active'
            
            item_label = item.get('label', '')
            item_icon = item.get('icon', '')
            item_url = item.get('url', '#')
            item_badge = item.get('badge', '')
            
            icon_html = f'<span class="nav-item-icon">{item_icon}</span>' if item_icon else ''
            badge_html = f'<span class="nav-item-badge">{item_badge}</span>' if item_badge else ''
            
            nav_items_html += f'''
<a href="{item_url}" class="{item_classes}">
    {icon_html}
    <span class="nav-item-label">{item_label}</span>
    {badge_html}
</a>'''
        
        nav_classes = f"{classes} nav-{position}"
        
        return f'''
<nav id="{component.component_id}" 
     class="{nav_classes}" 
     {attrs_str}{style_str}>
    {nav_items_html}
</nav>'''
    
    def _render_modal(self, component: ComponentProps) -> str:
        """渲染模态框组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        title = component.attributes.get('title', '')
        content = component.attributes.get('content', '')
        
        return f'''
<div id="{component.component_id}" class="modal {classes}" style="{styles}">
    <div class="modal-backdrop" data-dismiss="modal"></div>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">{title}</h4>
                <button type="button" class="modal-close" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                {content}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary">确定</button>
            </div>
        </div>
    </div>
</div>'''
    
    def _render_tabs(self, component: ComponentProps) -> str:
        """渲染标签页组件"""
        classes = ' '.join(component.classes)
        tabs = component.attributes.get('tabs', [])
        
        # 标签头
        tab_headers = ''
        tab_contents = ''
        
        for i, tab in enumerate(tabs):
            active_class = 'active' if i == 0 else ''
            tab_id = f"{component.component_id}_tab_{i}"
            
            tab_headers += f'''
<button class="tab-header {active_class}" 
        data-tab="{tab_id}"
        role="tab">
    {tab.get('label', f'标签{i+1}')}
</button>'''
            
            tab_contents += f'''
<div id="{tab_id}" 
     class="tab-content {active_class}"
     role="tabpanel">
    {tab.get('content', '')}
</div>'''
        
        return f'''
<div id="{component.component_id}" class="tabs {classes}">
    <div class="tab-headers" role="tablist">
        {tab_headers}
    </div>
    <div class="tab-contents">
        {tab_contents}
    </div>
</div>'''
    
    def _render_form(self, component: ComponentProps) -> str:
        """渲染表单组件"""
        classes = ' '.join(component.classes)
        
        # 渲染表单字段
        fields_html = ''
        for child in component.children:
            fields_html += self.render_component(child)
        
        return f'''
<form id="{component.component_id}" class="form {classes}">
    {fields_html}
    <div class="form-actions">
        <button type="submit" class="btn btn-primary">提交</button>
        <button type="reset" class="btn btn-secondary">重置</button>
    </div>
</form>'''
    
    def _render_generic(self, component: ComponentProps) -> str:
        """渲染通用组件"""
        classes = ' '.join(component.classes)
        styles = '; '.join([f"{k}: {v}" for k, v in component.styles.items()])
        
        return f'''
<div id="{component.component_id}" 
     class="{classes}" 
     style="{styles}">
    <!-- {component.component_type.value} 组件 -->
</div>'''
    
    def generate_component_css(self) -> str:
        """生成组件CSS样式"""
        try:
            css_rules = []
            
            # 基础样式
            css_rules.append(f"""
/* 移动端组件库基础样式 */
* {{
    box-sizing: border-box;
}}

body {{
    font-family: {self.theme_config['typography']['font_family']};
    line-height: {self.theme_config['typography']['line_heights']['normal']};
    color: {self.theme_config['colors']['text_primary']};
    background-color: {self.theme_config['colors']['background']};
    margin: 0;
    padding: 0;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}}

/* 触摸目标 */
.touch-target {{
    min-height: 44px;
    min-width: 44px;
    position: relative;
    cursor: pointer;
    -webkit-tap-highlight-color: rgba(0,0,0,0.1);
    touch-action: manipulation;
}}

.touch-friendly {{
    -webkit-tap-highlight-color: rgba(0,0,0,0.1);
    touch-action: manipulation;
}}

/* 按钮组件 */
.btn {{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: {self.theme_config['spacing']['sm']} {self.theme_config['spacing']['md']};
    border: none;
    border-radius: {self.theme_config['border_radius']['md']};
    font-size: {self.theme_config['typography']['font_sizes']['md']};
    font-weight: 500;
    text-decoration: none;
    transition: all 0.2s ease;
    user-select: none;
    position: relative;
    overflow: hidden;
}}

.btn-sm {{
    padding: {self.theme_config['spacing']['xs']} {self.theme_config['spacing']['sm']};
    font-size: {self.theme_config['typography']['font_sizes']['sm']};
}}

.btn-lg {{
    padding: {self.theme_config['spacing']['md']} {self.theme_config['spacing']['lg']};
    font-size: {self.theme_config['typography']['font_sizes']['lg']};
}}

.btn-primary {{
    background-color: {self.theme_config['colors']['primary']};
    color: white;
}}

.btn-primary:hover {{
    background-color: #1976D2;
    transform: translateY(-1px);
    box-shadow: {self.theme_config['shadows']['md']};
}}

.btn-secondary {{
    background-color: {self.theme_config['colors']['secondary']};
    color: white;
}}

.btn-success {{
    background-color: {self.theme_config['colors']['success']};
    color: white;
}}

.btn-warning {{
    background-color: {self.theme_config['colors']['warning']};
    color: white;
}}

.btn-error {{
    background-color: {self.theme_config['colors']['error']};
    color: white;
}}

.btn-disabled {{
    opacity: 0.6;
    cursor: not-allowed;
    pointer-events: none;
}}

.btn-loading {{
    pointer-events: none;
}}

.loading-spinner {{
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid transparent;
    border-top: 2px solid currentColor;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: {self.theme_config['spacing']['xs']};
}}

@keyframes spin {{
    0% {{ transform: rotate(0deg); }}
    100% {{ transform: rotate(360deg); }}
}}

/* 输入框组件 */
.input-group {{
    margin-bottom: {self.theme_config['spacing']['md']};
}}

.input-label {{
    display: block;
    margin-bottom: {self.theme_config['spacing']['xs']};
    font-size: {self.theme_config['typography']['font_sizes']['sm']};
    font-weight: 500;
    color: {self.theme_config['colors']['text_primary']};
}}

.input {{
    width: 100%;
    padding: {self.theme_config['spacing']['sm']} {self.theme_config['spacing']['md']};
    border: 1px solid #E0E0E0;
    border-radius: {self.theme_config['border_radius']['md']};
    font-size: {self.theme_config['typography']['font_sizes']['md']};
    background-color: white;
    transition: all 0.2s ease;
}}

.input:focus {{
    outline: none;
    border-color: {self.theme_config['colors']['primary']};
    box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}}

.input-error {{
    border-color: {self.theme_config['colors']['error']};
}}

.input-helper {{
    margin-top: {self.theme_config['spacing']['xs']};
    font-size: {self.theme_config['typography']['font_sizes']['xs']};
    color: {self.theme_config['colors']['text_secondary']};
}}

/* 卡片组件 */
.card {{
    background-color: white;
    border-radius: {self.theme_config['border_radius']['lg']};
    box-shadow: {self.theme_config['shadows']['sm']};
    overflow: hidden;
    transition: all 0.2s ease;
}}

.card:hover {{
    box-shadow: {self.theme_config['shadows']['md']};
    transform: translateY(-2px);
}}

.card-header {{
    padding: {self.theme_config['spacing']['md']};
    border-bottom: 1px solid #F0F0F0;
}}

.card-title {{
    font-size: {self.theme_config['typography']['font_sizes']['lg']};
    font-weight: 600;
    margin: 0;
    color: {self.theme_config['colors']['text_primary']};
}}

.card-subtitle {{
    font-size: {self.theme_config['typography']['font_sizes']['sm']};
    color: {self.theme_config['colors']['text_secondary']};
    margin-top: {self.theme_config['spacing']['xs']};
}}

.card-body {{
    padding: {self.theme_config['spacing']['md']};
}}

/* 列表组件 */
.list {{
    background-color: white;
    border-radius: {self.theme_config['border_radius']['md']};
    overflow: hidden;
}}

.list-item {{
    display: flex;
    align-items: center;
    padding: {self.theme_config['spacing']['md']};
    border-bottom: 1px solid #F0F0F0;
    transition: background-color 0.2s ease;
}}

.list-item:last-child {{
    border-bottom: none;
}}

.list-item:hover {{
    background-color: #F5F5F5;
}}

.list-item.active {{
    background-color: rgba(33, 150, 243, 0.1);
    border-left: 3px solid {self.theme_config['colors']['primary']};
}}

.list-item-icon {{
    margin-right: {self.theme_config['spacing']['md']};
    font-size: {self.theme_config['typography']['font_sizes']['lg']};
    color: {self.theme_config['colors']['text_secondary']};
}}

.list-item-content {{
    flex: 1;
}}

.list-item-action {{
    margin-left: {self.theme_config['spacing']['md']};
    color: {self.theme_config['colors']['text_secondary']};
}}

/* 导航组件 */
.nav {{
    display: flex;
    background-color: white;
    box-shadow: {self.theme_config['shadows']['sm']};
}}

.nav-bottom {{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    border-top: 1px solid #E0E0E0;
}}

.nav-item {{
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: {self.theme_config['spacing']['sm']};
    text-decoration: none;
    color: {self.theme_config['colors']['text_secondary']};
    transition: all 0.2s ease;
    position: relative;
}}

.nav-item.active {{
    color: {self.theme_config['colors']['primary']};
}}

.nav-item-icon {{
    font-size: {self.theme_config['typography']['font_sizes']['lg']};
    margin-bottom: {self.theme_config['spacing']['xs']};
}}

.nav-item-label {{
    font-size: {self.theme_config['typography']['font_sizes']['xs']};
    text-align: center;
}}

.nav-item-badge {{
    position: absolute;
    top: 4px;
    right: 4px;
    background-color: {self.theme_config['colors']['error']};
    color: white;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: {self.theme_config['border_radius']['full']};
    min-width: 18px;
    text-align: center;
}}

/* 模态框组件 */
.modal {{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2000;
    display: none;
}}

.modal.show {{
    display: flex;
    align-items: center;
    justify-content: center;
}}

.modal-backdrop {{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}}

.modal-dialog {{
    position: relative;
    max-width: 90%;
    max-height: 90%;
    margin: {self.theme_config['spacing']['md']};
}}

.modal-content {{
    background-color: white;
    border-radius: {self.theme_config['border_radius']['lg']};
    box-shadow: {self.theme_config['shadows']['lg']};
    overflow: hidden;
}}

.modal-header {{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: {self.theme_config['spacing']['md']};
    border-bottom: 1px solid #E0E0E0;
}}

.modal-title {{
    margin: 0;
    font-size: {self.theme_config['typography']['font_sizes']['lg']};
    font-weight: 600;
}}

.modal-close {{
    background: none;
    border: none;
    font-size: {self.theme_config['typography']['font_sizes']['xl']};
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
}}

.modal-body {{
    padding: {self.theme_config['spacing']['md']};
}}

.modal-footer {{
    display: flex;
    justify-content: flex-end;
    gap: {self.theme_config['spacing']['sm']};
    padding: {self.theme_config['spacing']['md']};
    border-top: 1px solid #E0E0E0;
}}

/* 响应式设计 */
@media (max-width: {self.breakpoints['sm']}) {{
    .btn {{
        width: 100%;
        margin-bottom: {self.theme_config['spacing']['sm']};
    }}
    
    .card {{
        margin: {self.theme_config['spacing']['sm']};
    }}
    
    .modal-dialog {{
        max-width: 95%;
        margin: {self.theme_config['spacing']['sm']};
    }}
}}

/* 触摸反馈 */
@media (hover: none) and (pointer: coarse) {{
    .touch-target:active {{
        background-color: rgba(0, 0, 0, 0.1);
    }}
    
    .btn:active {{
        transform: scale(0.98);
    }}
}}
""")
            
            return '\n'.join(css_rules)
            
        except Exception as e:
            components_logger.error(f"CSS生成失败: {str(e)}")
            return "/* CSS generation failed */"
    
    def get_component_library_info(self) -> Dict[str, Any]:
        """获取组件库信息"""
        return {
            'name': '移动端UI组件库',
            'version': '1.0.0',
            'supported_components': [comp_type.value for comp_type in ComponentType],
            'theme_colors': self.theme_config['colors'],
            'breakpoints': self.breakpoints,
            'features': {
                'touch_optimized': True,
                'responsive_design': True,
                'accessibility_support': True,
                'theme_customization': True,
                'gesture_support': True,
                'performance_optimized': True
            },
            'component_count': len(self.component_templates),
            'css_size_estimate': '~15KB (gzipped)'
        }


# 示例使用
if __name__ == "__main__":
    # 创建组件库
    component_lib = MobileComponentLibrary()
    
    print("=== 移动端UI组件库测试 ===")
    
    # 创建按钮组件
    print("1. 创建按钮组件")
    button = component_lib.create_component(ComponentType.BUTTON, {
        'id': 'primary_button',
        'size': 'large',
        'variant': 'primary',
        'attributes': {
            'text': '开始研究',
            'type': 'submit'
        },
        'events': {
            'onclick': 'startResearch()'
        }
    })
    
    button_html = component_lib.render_component(button)
    print(f"按钮HTML长度: {len(button_html)} 字符")
    
    # 创建卡片组件
    print("\n2. 创建卡片组件")
    card = component_lib.create_component(ComponentType.CARD, {
        'id': 'project_card',
        'attributes': {
            'title': 'AI研究项目',
            'subtitle': '人工智能在医疗诊断中的应用',
            'content': '项目进度: 75%'
        },
        'children': [
            {
                'type': 'button',
                'size': 'small',
                'variant': 'secondary',
                'attributes': {
                    'text': '查看详情'
                }
            }
        ]
    })
    
    card_html = component_lib.render_component(card)
    print(f"卡片HTML长度: {len(card_html)} 字符")
    
    # 创建导航组件
    print("\n3. 创建导航组件")
    navigation = component_lib.create_component(ComponentType.NAVIGATION, {
        'id': 'bottom_nav',
        'attributes': {
            'position': 'bottom',
            'items': [
                {'label': '首页', 'icon': '🏠', 'url': '/', 'active': True},
                {'label': '项目', 'icon': '📁', 'url': '/projects'},
                {'label': '分析', 'icon': '📊', 'url': '/analysis'},
                {'label': '协作', 'icon': '👥', 'url': '/collaboration', 'badge': '3'},
                {'label': '设置', 'icon': '⚙️', 'url': '/settings'}
            ]
        }
    })
    
    nav_html = component_lib.render_component(navigation)
    print(f"导航HTML长度: {len(nav_html)} 字符")
    
    # 生成CSS
    print("\n4. 生成组件CSS")
    css = component_lib.generate_component_css()
    print(f"CSS长度: {len(css)} 字符")
    
    # 获取组件库信息
    print("\n5. 组件库信息")
    info = component_lib.get_component_library_info()
    print(json.dumps(info, indent=2, ensure_ascii=False))